package com.ruoyi.report.controller;

import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ruoyi.common.core.domain.entity.SysDept;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.report.domain.DepotJsonDto;
import com.ruoyi.report.domain.ReportDc;
import com.ruoyi.station.domain.RateDTO;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.report.domain.ReportSc;
import com.ruoyi.report.service.IReportScService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

import javax.servlet.http.HttpServletResponse;

/**
 * 供应站Controller
 * 
 * @author ruoyi
 * @date 2024-10-15
 */
@RestController
@RequestMapping("/sc/sc")
public class ReportScController extends BaseController
{
    @Autowired
    private IReportScService reportScService;

    /**
     * 查询供应站列表
     */
    @PreAuthorize("@ss.hasPermi('sc:sc:list')")
    @GetMapping("/list")
    public TableDataInfo list(ReportSc reportSc)
    {
        startPage();
        List<ReportSc> list = reportScService.selectReportScList(reportSc);
        return getDataTable(list);
    }


    @GetMapping("/listNoPage")
    public TableDataInfo listNoPage(ReportSc reportSc)
    {
        List<ReportSc> list = reportScService.selectReportScListNoPage(reportSc);
        return getDataTable(list);
    }

    @Autowired
    private SysUserMapper userMapper;
    @Autowired
    private ISysDeptService deptService;
    /**
     * 导出供应站列表
     */
    @PreAuthorize("@ss.hasPermi('sc:sc:export')")
    @Log(title = "供应站", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ReportSc reportSc)
    {
        Gson gson = new Gson();
        List<ReportSc> list = reportScService.selectReportScList(reportSc);


        //查询出所有部门
        List<SysDept> sysDepts = deptService.selectDeptList(new SysDept());
        List<SysUser> sysUsers = userMapper.selectUserList(new SysUser());
        for (ReportSc sc : list) {
//            SysUser correspondingWork = sysUsers.stream()
//                    .filter(user -> user.getUserId().equals(sc.getWorkUserId()))
//                    .findFirst()
//                    .orElse(null);
//            sc.setWorkName(ObjectUtil.isNotEmpty(correspondingWork)?correspondingWork.getUserName():"");


            SysUser correspondingReport = sysUsers.stream()
                    .filter(user -> user.getUserId().equals(sc.getReportUserId()))
                    .findFirst()
                    .orElse(null);
            sc.setReportName(ObjectUtil.isNotEmpty(correspondingReport)?correspondingReport.getUserName():"");
            String extra2 = sc.getExtra2();
            Type userType = new TypeToken<List<Long>>() {}.getType();
            List<Long> uids = gson.fromJson(extra2, userType);

            List<SysUser> correspondingReports = sysUsers.stream()
                    .filter(user -> uids.contains(user.getUserId())) // Assumes `ReportUserId` is now a collection of user IDs
                    .collect(Collectors.toList());

            String workNames = correspondingReports.stream()
                    .map(SysUser::getUserName)
                    .collect(Collectors.joining(", "));

            sc.setWorkName(workNames);




            SysDept correspondingDept = sysDepts.stream()
                    .filter(dept -> dept.getDeptId().equals(sc.getDeptId()))
                    .findFirst()
                    .orElse(null);

            sc.setDeptName(ObjectUtil.isNotNull(correspondingDept)?correspondingDept.getDeptName():"");
            String rateJson = sc.getRateJson();
            if (StringUtils.isNotEmpty(rateJson)){
                Type listType = new TypeToken<List<RateDTO>>() {}.getType();

                List<RateDTO> rateList = gson.fromJson(rateJson, listType);
                String concatenatedNames = rateList.stream()
                        .map(a->{
                            return a.getLevel()+"密：(视温(摄氏度):"+a.getTemperature()+";视密(克/立方厘米)："+a.getDensity()+");化验单编号:"+a.getSno();

                        })  // Replace getRateName() with the actual getter
                        .collect(Collectors.joining(", "));
                sc.setRateName(concatenatedNames);
            }
        }
        ExcelUtil<ReportSc> util = new ExcelUtil<ReportSc>(ReportSc.class);
         util.exportExcel(response,list, "供应站数据");
    }

    /**
     * 获取供应站详细信息
     */
    @PreAuthorize("@ss.hasPermi('sc:sc:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(reportScService.selectReportScById(id));
    }
@Autowired
private TokenService tokenService;
    /**
     * 新增供应站
     */
    @PreAuthorize("@ss.hasPermi('sc:sc:add')")
    @Log(title = "供应站", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ReportSc reportSc)
    {
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        reportSc.setDeptId(loginUser.getUser().getDept().getDeptId());

        reportSc.setCreateTime(DateUtils.getNowDate());
        Integer i = reportScService.countTodayRecordsByDeptId(reportSc.getDeptId());
        if (i>=1){
            throw new RuntimeException("今日已有数据上报记录,请前往修改");
        }
        Gson gson = new Gson();
        List<DepotJsonDto> extra1 = reportSc.getExtra1();
        List<DepotJsonDto> sendJson = reportSc.getSendJson();
        if (CollectionUtil.isNotEmpty(extra1)){
            reportSc.setExtra3(gson.toJson(extra1));
            reportSc.setExtra4(gson.toJson(sendJson));
        }
        List<Map> rate = reportSc.getRate();

        reportSc.setRateJson(gson.toJson(rate));
        reportSc.setExtra1(null);
        reportSc.setSendJson(null);
        List<Long> workUsers = reportSc.getWorkUsers();
        if (CollectionUtil.isNotEmpty(workUsers)){
            reportSc.setExtra2(gson.toJson(workUsers));
        }

        List<Long> cars = reportSc.getCars();
        if (CollectionUtil.isNotEmpty(cars)){
            reportSc.setCarId(gson.toJson(cars));
        }

        return toAjax(reportScService.insertReportSc(reportSc));
    }

    /**
     * 修改供应站
     */
    @PreAuthorize("@ss.hasPermi('sc:sc:edit')")
    @Log(title = "供应站", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ReportSc reportSc)
    {
        Gson gson = new Gson();
        List<DepotJsonDto> extra1 = reportSc.getExtra1();
        List<DepotJsonDto> sendJson = reportSc.getSendJson();
        if (CollectionUtil.isNotEmpty(extra1)){
            reportSc.setExtra3(gson.toJson(extra1));
            reportSc.setExtra4(gson.toJson(sendJson));
        }
        List<Map> rate = reportSc.getRate();

        reportSc.setRateJson(gson.toJson(rate));


        reportSc.setExtra1(null);
        reportSc.setSendJson(null);
        List<Long> workUsers = reportSc.getWorkUsers();
        if (CollectionUtil.isNotEmpty(workUsers)){
            reportSc.setExtra2(gson.toJson(workUsers));
        }

        List<Long> cars = reportSc.getCars();
        if (CollectionUtil.isNotEmpty(cars)){
            reportSc.setCarId(gson.toJson(cars));
        }
        return toAjax(reportScService.updateReportSc(reportSc));
    }

    /**
     * 删除供应站
     */
    @PreAuthorize("@ss.hasPermi('sc:sc:remove')")
    @Log(title = "供应站", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(reportScService.deleteReportScByIds(ids));
    }
}
